const mongoose = require("mongoose");
const Report = require("../models/reportModel");
const User = require("../models/userModel");

//增加调研报告
exports.createReport = async (req, res) => {
  try {
    console.log("kkkkk", req.body);
    const newReport = await Report.create(req.body);
    req.user.reportNumber++;
    await User.findByIdAndUpdate(req.user._id, req.user, {
      new: true,
    });
    // 201 Created 已创建
    res.status(201).json({
      status: "success",
      data: newReport,
    });
  } catch (err) {
    console.log("创建调研报告失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//删除调研报告
exports.deleteReport = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.params);
    req.user.reportNumber--;
    await User.findByIdAndUpdate(req.user._id, req.user, {
      new: true,
    });
    const data = await Report.deleteOne({ _id: id });
    res.status(200).json({
      status: "success",
      data: data,
    });
  } catch (err) {
    console.log("删除调研报告失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//修改调研报告状态（通过/驳回）
exports.updateReport = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.params);
    const newReport = await Report.findByIdAndUpdate(id, req.body, {
      new: true,
    });
    if (!newReport) {
      return res.status(404).json({
        message: "审批的调研报告并不存在",
      });
    }
    res.status(200).json({
      status: "success",
      data: newReport,
    });
  } catch (err) {
    console.log("修改调研报告状态失败", err);
    res.status(404).json({
      err,
    });
  }
};

//根据用户id获取调研报告 （用户）
exports.getReportByUserId = async (req, res) => {
  try {
    const userId = mongoose.Types.ObjectId(req.params);
    const reportList = await Report.find({ userId: userId });
    res.status(200).json({
      status: "success",
      data: reportList,
    });
  } catch (err) {
    console.log("根据用户id获取调研报告失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

// //获取所有调研报告 （审核员）
// exports.getAllReport = async (req, res) => {
//   try {
//     const scoreList = await Score.find()
//       .populate({ path: "userId", select: "name group" })
//       .populate({ path: "testId", select: "title" });
//     res.status(200).json({
//       status: "success",
//       data: scoreList,
//     });
//   } catch (err) {
//     console.log("获取所有成绩记录失败", err);
//     res.status(404).json({
//       Error: err,
//     });
//   }
// };
